package com.netsdk.demo.lht;

import com.alibaba.fastjson.JSON;
import com.netsdk.demo.util.CaseMenu;
import com.netsdk.demo.util.sql.JdbcUtils;
import com.netsdk.demo.util.sql.TrafficFlowStateDto;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.enumeration.*;
import com.netsdk.lib.structure.NET_VEHICLE_INOUT_ANALYSE_PROC;
import com.netsdk.lib.utils.Initialization;
import com.sun.jna.Pointer;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Objects;

public class TrafficFlowStatDemo extends Initialization {


    int channel= -1;

    NetSDKLib.LLong    attachHandle=new NetSDKLib.LLong(0);
    /**
     * 订阅智能任务
     */

    public NetSDKLib.LLong AttachEventRealLoadPic() {
        // 先退订，设备不会对重复订阅作校验，重复订阅后会有重复的事件返回
        if(attachHandle.longValue()!=0){
            this.DetachEventRealLoadPic();
        }

        // 需要图片
        int bNeedPicture = 1;
        attachHandle = netSdk.CLIENT_RealLoadPictureEx(loginHandle, channel, EM_EVENT_TYPE.EVENT_IVS_ALL.getType(), bNeedPicture,
                AnalyzerDataCB.getInstance(), null, null);
        if (attachHandle.longValue() != 0) {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Success\n", channel);
        } else {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Failed!LastError = %s\n", channel,
                    ToolKits.getErrorCode());
        }

        return attachHandle;
    }


    


    /**
     * 报警事件（智能）回调
     */
    private static class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack {
        private final File picturePath;
        private static AnalyzerDataCB instance;

        private AnalyzerDataCB() {
            picturePath = new File("./AnalyzerPicture/");
            if (!picturePath.exists()) {
                picturePath.mkdirs();
            }
        }

        public static AnalyzerDataCB getInstance() {
            if (instance == null) {
                instance = new AnalyzerDataCB();
            }
            return instance;
        }

        @Override
        public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType, Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved) throws UnsupportedEncodingException {
            if (lAnalyzerHandle == null || lAnalyzerHandle.longValue() == 0) {
                return -1;
            }
//            System.out.println(Objects.requireNonNull(EM_EVENT_IVS_TYPE.getEventType(dwAlarmType)).getDescription());
            switch (Objects.requireNonNull(EM_EVENT_IVS_TYPE.getEventType(dwAlarmType))) {
                case  EVENT_IVS_TRAFFIC_FLOWSTATE : {
                    System.out.println("===================================EVENT RECEIVED=======================================");
//                    System.out.println("交通流量事件, code = " + dwAlarmType);
//
                    NetSDKLib.DEV_EVENT_TRAFFIC_FLOW_STATE msg = new NetSDKLib.DEV_EVENT_TRAFFIC_FLOW_STATE();
                    ToolKits.GetPointerData(pAlarmInfo, msg);
                    System.out.println(JSON.toJSONString(msg));

                    // 插入数据库
                    TrafficFlowStateDto trafficFlowStateDto = TrafficFlowStateDto.init(msg);
                    JdbcUtils.insert(trafficFlowStateDto);

                    // 通道号
//                    int nChannelID = msg.nChannelID;
//                    System.out.println("nChannelID:" + nChannelID);
//                    //事件名称
//                    byte[] szName = msg.szName;
//                    System.out.println("szName:" + new String(szName).trim());
//                    // 规则编号
//                    int nRuleID = msg.nRuleID;
//                    System.out.println("nRuleID:" + nRuleID);
//                    //相对事件时间戳(单位是毫秒)
//                    double pts = msg.PTS;
//                    System.out.println("pts:" + new Date((long) pts));
//                    //UTC时间
//                    NetSDKLib.NET_TIME_EX UTC = msg.UTC;
//                    System.out.println("UTC:" + UTC.toStringTime());
//                    //事件id
//                    int nEventID = msg.nEventID;
//                    System.out.println("nEventID:" + nEventID);
//                    //序号
//                    int Sequence = msg.nSequence;
//                    System.out.println("nSequence:" + Sequence);
//                    //流量状态数量
//                    int nStateNum = msg.nStateNum;
//                    System.out.println("nStateNum:" + nStateNum);
//                    //流量状态
//                    for(int i = 0; i < nStateNum; i ++){
//                        System.out.println("stuStates[" + i + "]:" + msg.stuStates[i].toString());
//                    }
//                    //该事件触发的预置点
//                    int nPresetID = msg.stuIntelliCommInfo.nPresetID;
//                    System.out.println("nPresetID:" + nPresetID);
//                    //智能事件所属大类
//                    String emClassType = EM_CLASS_TYPE.getNoteByValue(msg.stuIntelliCommInfo.emClassType);
//                    System.out.println("emClassType:" + emClassType);
//                    //流量状态数量
//                    int nStopVehiclenum = msg.nStopVehiclenum;
//                    System.out.println("nStopVehiclenum:" + nStopVehiclenum);
//                    //流量状态数量
//                    int nDetectionAreaVehicleNum = msg.nDetectionAreaVehicleNum;
//                    System.out.println("nDetectionAreaVehicleNum:" + nDetectionAreaVehicleNum);
//                    //溢出状态
//                    for(int i = 0; i < msg.nStateNum; i ++){
//                        int emOverflowState = msg.stuStates[i].emOverflowState;
//                        System.out.println("emOverflowState[" + i + "]:" +  NET_EM_OVER_FLOW_STATE.getNoteByValue(emOverflowState));
//                    }
//                    //图片保存
//                    if (msg != null) {
//                        String picture = picturePath + "/" + System.currentTimeMillis() + "related_TrafficFlowState.jpg";
//                        System.out.println("Picture saved, the path is  " + picture);
////                        ToolKits.savePicture(pBuffer, dwBufSize, picture);
//                    }
                    break;
                }
//                case EVENT_IVS_TRAFFICJUNCTION: ///<
//                {
//                    System.out.println(" 路口事件");
//                    NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO msg = new NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO();
//                    ToolKits.GetPointerData(pAlarmInfo, msg);
//
//                    System.out.println(JSON.toJSONString(msg));
//
//                    try {
//                        System.out.println(new String(msg.stuObject.szText, "GBK").trim());
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }
//
//                    break;
//                }
                case EVENT_IVS_TRAFFIC_PARKING:
                    System.out.println("停車檢測");
                    NetSDKLib.DEV_EVENT_TRAFFIC_PARKING_INFO msg = new NetSDKLib.DEV_EVENT_TRAFFIC_PARKING_INFO();
                    ToolKits.GetPointerData(pAlarmInfo, msg);
                    formatObj(msg.stuVehicle);
                    System.out.println("22222222222222222222");
                    formatObj(msg.stuObject);
                    System.out.println(JSON.toJSONString(msg));
                default:
                    System.out.println("其他事件--------------------"+ EM_EVENT_IVS_TYPE.getEventType(dwAlarmType));
                    break;
            }
            return 0;
        }
    }

    private static void formatObj(NetSDKLib.NET_MSG_OBJECT obj){
        Charset charset = Charset.forName("UTF-8");
        if (filter(obj.szObjectType)){
            System.out.println("物体类型："+new String(obj.szObjectType,charset) );
        }
        if(filter(obj.byColorSimilar)){
            System.out.println("byColorSimilar："+new String(obj.byColorSimilar, charset));
        }
        if (filter(obj.szObjectSubType)){
            System.out.println("szObjectSubType："+new String(obj.szObjectSubType, charset));
        }
        if (filter(obj.szText)){
            System.out.println("szText："+new String(obj.szText, charset));
        }
        if (filter(obj.szSubText)){
            System.out.println("szSubText："+new String(obj.szSubText, charset));
        }
    }
    private static boolean filter(byte[] arr){
        if (arr==null)return false;
        if (arr[0] != 0){
            return true;
        }
        return false;
    }
    /**
     * 停止侦听智能事件
     */
    public void DetachEventRealLoadPic() {
        if (this.attachHandle.longValue() != 0) {
            netSdk.CLIENT_StopLoadPic(this.attachHandle);
        }
    }
    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem((new CaseMenu.Item(this , "AttachEventRealLoadPic" , "AttachEventRealLoadPic")));
        menu.addItem((new CaseMenu.Item(this , "DetachEventRealLoadPic" , "DetachEventRealLoadPic")));

        menu.run();
    }

    public static void main(String[] args) {
        TrafficFlowStatDemo RealLoadPicExDemo=new TrafficFlowStatDemo();
        Initialization.InitTest("10.238.87.39", 37777, "admin", "huichen123!@#");
        RealLoadPicExDemo.RunTest();
        LoginOut();

    }
}
